"use client";
import {Avatar, Button, Card, Col, Row, Modal, Form, Input, message, Tag} from "antd";
import {useDispatch, useSelector} from "react-redux";
import {AppDispatch, RootState} from "@/stores";
import Title from "antd/es/typography/Title";
import Paragraph from "antd/es/typography/Paragraph";
import React, {useState, useEffect} from "react";
import CalendarChart from "@/app/user/center/components/CalendarChart";
import "./index.css";
import {changePasswordUsingPost, updateUserUsingPost} from "@/api/userController";
import {setLoginUser} from "@/stores/loginUser";
import {DEFAULT_USER} from "@/constants/user";
import {useRouter} from "next/navigation";
import ThumbQuestion from "@/app/user/center/components/ThumbQuestion";
import FavorQuestionsPage from "@/app/user/center/components/FavorQuestion";
import {getUserInfoUsingGet} from "@/api/userController";

/**
 * 用户中心页面
 * @constructor
 */
export default function UserCenterPage() {
    // 获取登录用户信息
    const loginUser = useSelector((state: RootState) => state.loginUser);
    // 便于复用，新起一个变量
    const user = loginUser;
    // 控制菜单栏的 Tab 高亮
    const [activeTabKey, setActiveTabKey] = useState<string>("record");

    // 新增密码修改相关状态
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [form] = Form.useForm();
    const dispatch = useDispatch<AppDispatch>();
    const router = useRouter();

    // 显示修改密码弹窗
    const showPasswordModal = () => setIsModalOpen(true);

    // 提交修改密码
    const handlePasswordSubmit = async (values: API.UserUpdateMyRequest) => {
        try {
            const res = await changePasswordUsingPost(values);
            if (res.data) {
                message.success("修改成功");
                // 删除用户登录状态并跳转到登录页面
                dispatch(setLoginUser(DEFAULT_USER));
                router.replace("/user/login");
            }
        } catch (e) {
            message.error("修改失败" + e.message);
        }
    };

    return (
        <div id="userCenterPage" className="max-width-content">
            <Row gutter={[16, 16]}>
                <Col xs={24} md={6}>
                    <Card style={{textAlign: "center"}}>
                        <Avatar src={user.userAvatar} size={72}/>
                        <div style={{marginBottom: 16}}/>
                        <Card.Meta
                            title={
                                <Title level={4} style={{marginBottom: 0}}>
                                    {user.userName}
                                    {/* 新增VIP标识 */}
                                    <Tag color={user.isVip === 1 ? 'gold' : 'gray'} style={{ marginTop: '-100px' }}>
                                        {user.isVip === 1 ? 'VIP' : 'VIP'}
                                    </Tag>
                                </Title>
                            }
                            description={
                                <>
                                    <Paragraph type="secondary">{user.userProfile}</Paragraph>
                                    <Button
                                        type="link"
                                        onClick={showPasswordModal}
                                        style={{padding: 0}}
                                    >
                                        修改密码
                                    </Button>
                                </>
                            }
                        />
                    </Card>
                </Col>
                <Col xs={24} md={18}>
                    <Card
                        tabList={[
                            {
                                key: "record",
                                label: "刷题记录",
                            },
                            {
                                key: "myThumb",
                                label: "我的点赞",
                            },
                            {
                                key: "myFavor",
                                label: "我的收藏",
                            }
                        ]}
                        activeTabKey={activeTabKey}
                        onTabChange={(key: string) => {
                            setActiveTabKey(key);
                        }}
                    >
                        {activeTabKey === "record" && (
                            <>
                                <CalendarChart/>
                            </>
                        )}
                        {activeTabKey === "myThumb" && (
                            <>
                                <ThumbQuestion/>
                            </>
                        )}
                        {activeTabKey === "myFavor" && (
                            <>
                                <FavorQuestionsPage/>
                            </>
                        )}
                    </Card>
                </Col>
            </Row>
            {/* 密码修改弹窗 */}
            <Modal
                title="修改密码"
                open={isModalOpen}
                onCancel={() => setIsModalOpen(false)}
                footer={null}
                destroyOnClose
            >
                <Form
                    form={form}
                    onFinish={handlePasswordSubmit}
                    layout="vertical"
                    requiredMark={false}
                >
                    <Form.Item
                        label="当前密码"
                        name="currentPassword"
                        rules={[{required: true, message: "请输入当前密码"}]}
                    >
                        <Input.Password placeholder="请输入当前密码"/>
                    </Form.Item>

                    <Form.Item
                        label="新密码"
                        name="newPassword"
                        rules={[
                            {required: true},
                            {
                                min: 8,
                                message: "密码长度至少8位"
                            },
                            {
                                pattern: /^(?=.*[a-zA-Z])(?=.*\d).+/,
                                message: "必须包含字母和数字"
                            }
                        ]}
                    >
                        <Input.Password placeholder="请输入新密码"/>
                    </Form.Item>

                    <Form.Item
                        label="确认新密码"
                        name="confirmPassword"
                        dependencies={['newPassword']}
                        rules={[
                            {required: true},
                            ({getFieldValue}) => ({
                                validator(_, value) {
                                    if (!value || getFieldValue('newPassword') === value) {
                                        return Promise.resolve();
                                    }
                                    return Promise.reject(new Error('两次输入的密码不一致'));
                                },
                            }),
                        ]}
                    >
                        <Input.Password placeholder="请确认新密码"/>
                    </Form.Item>

                    <Form.Item>
                        <Button
                            type="primary"
                            htmlType="submit"
                            block
                            style={{marginTop: 16}}
                        >
                            确认修改
                        </Button>
                    </Form.Item>
                </Form>
            </Modal>
        </div>
    );
}

